package com.base.components.common.doc.swagger2;

import com.base.components.common.doc.annotation.ApiExtension;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;

import java.util.List;

/**
 * OperationExtensionReader 读取拓展信息
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version v1.0.0
 * @date 2018-12-14 16:32
 */
public class OperationExtensionReader implements OperationBuilderPlugin {
  @Autowired
  private DescriptionResolver descriptions;

  @Override
  public void apply(OperationContext context) {
    Optional<ApiExtension> extension = context.findAnnotation(ApiExtension.class);
    if(extension.isPresent()){
      ApiExtension e = extension.get();
      StringBuffer notes = new StringBuffer("[AUTHOR : ")
        .append(e.author()).append("], [UPDATE : ").append(e.update()).append("]");
      Optional<ApiOperation> optional = context.findAnnotation(ApiOperation.class);
      if(optional.isPresent()){
        notes.append("\n").append(optional.get().notes());
      }
      context.operationBuilder().notes(descriptions.resolve(notes.toString()));
      List<VendorExtension> extensions = Lists.newArrayList();
      if(StringUtils.isNotBlank(e.author())){
        extensions.add(new StringVendorExtension("AUTH", e.author()));
      }
      if(StringUtils.isNotBlank(e.update())){
        extensions.add(new StringVendorExtension("UPDATE", e.update()));
      }
      if(!extensions.isEmpty()){
        context.operationBuilder().extensions(extensions);
      }
    }
  }

  @Override
  public boolean supports(DocumentationType delimiter) {
    return true;
  }
}
